package com.loan.controller;

import com.loan.dto.Result;
import com.loan.util.DateUtils;
import com.loan.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by huxudong on 17/7/10.
 */
@Controller
@RequestMapping("file")
public class FileUploadController {

    @RequestMapping(value = "/single", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result single(@RequestParam(value = "file", required = true) MultipartFile file, @RequestParam(value = "path",required = false,defaultValue = "common")String pathinfo) {
        if (!file.isEmpty()) {
            String success = "";
            try {

                String rootpath = "/usr/local/soft";
                String filepath = "/upload/"+pathinfo+"/" + DateUtils.getDate("yyyyMMdd") + "/";
                String fileOriginalName = file.getOriginalFilename();
                String newfilename = DateUtils.getDate("HHmmss")+ fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
                File newfile = new File(rootpath+filepath+newfilename);
                //FileUtil.SaveFileByPhysicalDir(rootpath+filepath+newfilename,file.getInputStream());
                FileUtil.CreateDirectory(new File(rootpath+filepath));
                //文件写入磁盘
                file.transferTo(newfile);
                success = filepath + newfilename;
                return new Result(200,success);

            } catch (FileNotFoundException e) {
                e.printStackTrace();

                return new Result(601,"上传失败，文件处理异常，稍后重试");
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(601,"上传失败，文件处理异常，稍后重试");
            }
        } else {
            return new Result(601,"上传失败，文件为空");
        }
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.getDate("HHmmss"));
    }
}
